﻿$(function () {
    // CRUD MailingList
    $("#ddlSource").live("change", function () {
        $("#PageIndex").val(1);
        $("#GetRequestListForm").submit();
    });
    $('#imgPublishTime').bind("click", function () {
        $('#PublishTime').focus();
    });

    $(".chkCity").click(function () {
        var selectedId = $(this).attr("id");
        if ($(this).is(':checked')) {
            $(".chkCity").each(function () {
                if ($(this).attr("id") != selectedId)
                    $(this).attr("checked", false);
            });

        }
    });

    $(".chkCategory").click(function () {
        var selectedId = $(this).attr("id");
        if ($(this).is(':checked')) {
            $(".chkCategory").each(function () {
                if ($(this).attr("id") != selectedId)
                    $(this).attr("checked", false);
            });

        }
    });

    $(".chkGender").click(function () {
        var selectedChk = $(this);
        if ($(this).is(':checked')) {
            $(".chkGender").each(function () {
                $(this).attr("checked", false);
            });

            selectedChk.attr("checked", true);
        }
    });

    $("#ddlTemplateList").live("change", function () {
        var templateName = $(this).val();
        var errorMsg = "Lỗi khi load dữ liệu, vui lòng thử lại.";
        $.BigLoading();
        $.post('/MailingList/JsonTemplateBuilder', { 'templateName': templateName })
               .done(function (json) {
                   json = json || {};

                   $.RemoveBigLoading();
                   if (json.success) {
                       $("#divTemplateBuilder").replaceWith(json.Html);
                       $("#TemplateName").val(templateName);
                   } else {
                       alert(json.Message);
                   }
               })
               .error(function () {
                   alert(errorMsg);
               });
    });

    $(".txtItemId").live('keypress', function (e) {
        if (e.keyCode == 13) {
            var type = $(this).attr("itemtype");
            var divDeal = $(this).parents('div:eq(0)');

            var dealId = parseInt($(this).val());
            if (isNaN(dealId) || dealId < 0) {
                FillJsonToDeal(divDeal, null);
                alert("Mã SP không hợp lệ");
                return;
            }
            if (dealId == 0) return;

            LoadDealInfo(dealId, type, divDeal);
            e.preventDefault();
        }
    });

    $("#btnBuildTemplate").live("click", function () {
        var errorMsg = "Lỗi khi load parse email template, vui lòng kiểm tra lại.";
        var form = $("#frmSendML");
        var divPreviewHtml = $("#divPreviewHtml").html();
        if (divPreviewHtml == '') {
            alert("Vui lòng chọn email template");
            return;
        }
        $.BigLoading();
        $.post("/MailingList/JsonPreViewGenerateTemplate",
                form.serialize(),
                function (json) {
                    $.RemoveBigLoading();
                    json = json || {};
                    if (json.success) {

                        $("#divPreviewHtml").html(json.Html);

                    } else {
                        alert(json.Message);
                    }
                });
    });

    $("#btnSaveTemplate").live("click", function () {
        var errorMsg = "Lỗi khi load dữ liệu, vui lòng thử lại.";
        var name = $("#ddlTemplateList").val();
        var cityName = $("#ddlCityList option:selected").text();
        var html = $("#divPreviewHtml").html();
        if (html == '') {
            alert("Bạn chưa tạo nội dung email.");
            return;
        }

        $.BigLoading();
        $.post('/MailingList/DownloadTemplateHtml', { 'TemplateName': name, 'CityName': cityName, 'Html': html },
        function (json) {
            json = json || {};
            $.RemoveBigLoading();
            if (json.success) {

                window.open(json.RedirectUrl, "Lưu template");

            } else {
                alert(errorMsg);
            }
        });
    });

    $("#btnGoToCRUMailingListForm").live("click", function () {

        var name = $("#ddlTemplateList").val();
        var cityName = $("#ddlCityList option:selected").text();
        var html = $("#divPreviewHtml").html();
        if (html == '') {
            alert("Bạn chưa tạo nội dung email.");
            return;
        }

        $.BigLoading();
        $.post('/MailingList/SaveTemplateHtml', { 'TemplateName': name, 'CityName': cityName, 'Html': html },
        function (json) {
            json = json || {};

            $.RemoveBigLoading();
            if (json.success) {

                window.location = "/MailingList/CRUMailingList?savedTemplate=" + json.TemplateFileName;

            } else {
                alert(json.Message);
            }
        });
    });

    $("#ddlCityList").live("change", function () {
        ClearItemInputDat();
    });
});

function LoadMailingList(id) {
    window.location = "/MailingList/CRUMailingList?mode=Edit&id=" + id;
}

function PreviewEmailTemplate(id) {
    var url = "/MailingList/PreviewEMailTemplate?id=" + id;
    window.open(url, "Xem trước email template");
}

/* Send MailingList */

function LoadDealInfo(id, type, targetDiv) {
    var action = '/MailingList/JsonLoadDealInfo';
    var errorMsg = "Lỗi khi load dữ liệu, vui lòng thử lại.";
    var source = $("#TemplateItemSource").val();
    var cityId = $("#ddlCityList").val();

    $.BigLoading();
    $.post(action, { 'id': id, 'type': type, 'source': source, 'cityId': cityId },
    function (json) {
        json = json || {};
        $.RemoveBigLoading();
        if (json.success) {

            FillJsonToDeal(targetDiv, json.Deal);

            var built = "";
            $.each(json.Deal.ListImageUrl, function (j, imageUrl) {
                //build image here
                var css = "";
                if (json.Deal.ImageUrl == imageUrl)
                    css = " class='active' ";
                built += '<img width=' + '"' + '50' + '"' + 'height=' + '"' + 50 + '"' + css + 'src="' + imageUrl + '"' + 'alt=' + '"' + '[img]' + '"' + 'onclick=' + '"' + 'SelectDealImage(this)' + '"' + 'style="margin:4px 4px 0px 0px;cursor:pointer;"' + '/>';
            });
            targetDiv.find(".divImageExtend").html(built);

        } else {
            FillJsonToDeal(targetDiv, null);
            alert(json.Message);
        }
    });
}

function ClearItemInputDat() {
    $(".divItem").each(function () {
        FillJsonToDeal($(this), null);
    });
}

function FillJsonToDeal(targetDiv, json) {
    if (json != null) {
        targetDiv.find("input[id$='ItemId']").val(json.ItemId);
        targetDiv.find("input[id$='ItemName']").val(json.ItemName);
        targetDiv.find("input[id$='Discount']").val(json.Discount);
        targetDiv.find("input[id$='Price']").val(json.Price);
        targetDiv.find("input[id$='Value']").val(json.Value);
        targetDiv.find("textarea[id$='Description']").val(json.Description);
        targetDiv.find("textarea[id$='Address']").val(json.Address);
        targetDiv.find("input[id$='ImageUrl']").val(json.ImageUrl);
        targetDiv.find("input[id$='LinkDetail']").val(json.LinkDetail);
    }
    else {
        targetDiv.find("input[id$='ItemId']").val('');
        targetDiv.find("input[id$='ItemName']").val('');
        targetDiv.find("input[id$='Discount']").val('');
        targetDiv.find("input[id$='Price']").val('');
        targetDiv.find("input[id$='Value']").val('');
        targetDiv.find("textarea[id$='Description']").val('');
        targetDiv.find("textarea[id$='Address']").val('');
        targetDiv.find("input[id$='ImageUrl']").val('');
        targetDiv.find("input[id$='LinkDetail']").val('');
        targetDiv.find(".divImageExtend").html("");
    }
}

function SelectDealImage(img) {
    var src = $(img).attr("src");
    //var divImg = $(img).parents('div:eq(0)');
    var divDeal = $(img).parents('div:eq(1)');
    var txtImgUrl = divDeal.find(".imgUrlTextBox");
    txtImgUrl.val(src);

    divDeal.find("img").each(function () {
        $(this).removeClass("active");
    });
    $(img).addClass("active");
}

function SendSampleEmail() {
    var errorMsg = "Lỗi khi load dữ liệu, vui lòng thử lại.";
    var email = $("#EmailTesting").val();
    var name = $("#ddlTemplateList").val();
    var html = $("#divPreviewHtml").html();
    var cityName = $("#ddlCityList option:selected").text();

    if (html == '') {
        alert("Bạn chưa tạo nội dung email.");
        return;
    }

    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (email == '' || !filter.test(email)) {
        alert("Email không hợp lệ");
        return;
    }

    $.BigLoading();
    $.post('/MailingList/JsonSendSampleEmail', { 'TemplateName': name, 'Html': html, 'Email': email, 'CityName': cityName, 'ItemSource': $("#TemplateItemSource").val() },
    function (json) {
        json = json || {};
        $.RemoveBigLoading();
        if (json.success) {

            alert("Gửi email thành công");

        } else {
            alert(json.Message);
        }
    });
}

function setTemplateItemSource(source) {
    if ($("#TemplateItemSource").val() != source) {
        ClearItemInputDat();
    }
    $("#TemplateItemSource").val(source);
}